<template>
  <div class="newassetBox disabled">
    <el-form ref="assetForm" :model="assetForm" :rules="rules" label-width="100px">
      <el-form-item label="封面：" class="coverUpload">
        <img v-if="assetForm.imgUrl" :src="assetForm.imgUrl" style="width:180px;height:120px;">
        <img v-if="!assetForm.imgUrl" src="../../../assets/user_images/language.png" style="width:180px;height:120px;">
        <el-upload
          v-if="!disable"
          :on-change="handleChange"
          :http-request="uploadFile"
          :limit="1"
          action=""
          class="upload-demo"
          accept="image/jpg, image/png"
        >
          <el-button slot="trigger" type="primary">上传封面</el-button>
        </el-upload>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="名称：" prop="name">
            <el-input v-model="assetForm.name" :disabled="disable" placeholder="请输入名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="描述：" prop="description">
            <el-input v-model="assetForm.description" :disabled="disable" placeholder="请输入描述"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="时长：" prop="duration">
            <el-input v-model="assetForm.duration" :disabled="disable" placeholder="请输入时长(/小时)"/>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="价格：" prop="price">
            <el-input v-model="assetForm.price" :disabled="disable" placeholder="请输入价格(/元)"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="类型：" prop="genre">
            <el-select v-model="assetForm.assetsType" :disabled="disable" placeholder="请选择" style="width:100%;">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="assetForm.assetsType==='live'" :gutter="20">
        <el-col :span="10">
          <el-form-item :prop="assetForm.assetsType==='live' ? 'stratTime' : ''" label="开始时间：">
            <el-date-picker
              v-model="assetForm.startTime"
              :disabled="disable"
              type="datetime"
              placeholder="选择日期时间"
              style="width:100%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item :prop="assetForm.assetsType==='live' ? 'endTime' : ''" label="结束时间：">
            <el-date-picker
              v-model="assetForm.endTime"
              :disabled="disable"
              type="datetime"
              placeholder="选择日期时间"
              style="width:100%;"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-card v-if="assetForm.assetsType!=='live'" shadow="hover" style="margin:0 40px;">
        <el-row>
          <el-col :span="7">
            <div class="search-wrap">
              <el-input
                v-model="keyword"
                clearable
                style="width:150px;"
                placeholder="附件名称"
                @keyup.enter.native="handleFilter"
              />
              <el-button type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
              <el-button size="medium" type="info" @click="clearParams">清空</el-button>
            </div>
          </el-col>
          <el-col v-if="progressHidden" :span="13" style="margin-top: 6px;">
            <el-progress :text-inside="true" :stroke-width="24" :percentage="percentage" status="success"/>
          </el-col>
          <el-col :span="2" :offset="2" style="float: right;">
            <el-upload
              v-if="!disable"
              :before-upload="handleBefore"
              :on-change="handleChange"
              :http-request="uploadFileEnclosure"
              :show-file-list="false"
              action=""
              class="upload-demo"
            >
              <el-button slot="trigger" type="primary">新增课件</el-button>
            </el-upload>
          </el-col>
        </el-row>
        <el-table
          :data="enclosureTableData"
          :default-sort="{prop: 'typeIndex', order: 'ascending'}"
          border
          style="width: 100%;text-align:center;margin-top:20px;"
        >
          <el-table-column label="编号" align="center" width="100">
            <template slot-scope="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="课件名称" sortable prop="name" align="center" width="300"/>
          <el-table-column label="课件存储路径" sortable prop="fileUrl" align="center"/>
          <el-table-column label="课件上传时间" sortable prop="createTimeStr" align="center" width="200"/>
          <el-table-column v-if="!disable" label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteEnclosure(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          :total="total"
          :current-page="currentpage"
          :page-size="pagesize"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
        />
      </el-card>
      <el-row v-if="!disable" :gutter="20" style="margin:20px 0">
        <el-col :span="3" :offset="17">
          <el-button type="primary" @click="saveForm">保存</el-button>
          <el-button @click="cancelForm">取消</el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
  import Pagination from '@/components/Pagination' // 分页组件
  import {addAssetsUnit, addEnclosureFromVideo, clearPercent, delEnclosureById, getCreateUploadVideoUrl, getEnclosureList, getRefreshUploadVideoInfo, saveUsedRecord, showPercent, updateAssetsUnit, upLoadFileToOss} from '@/api/subject/digitalAssets' // 数据接口
  import {upLoadFile} from '@/api/upLoadFile'
  import {getTenantId, getUserId, getUserName} from '@/utils/auth'

  export default {
    components: {
      Pagination
    },
    data() {
      return {
        total: 0,
        currentpage: 1,
        pagesize: 5,
        fileList: [],
        keyword: '',
        assetForm: {
          name: '',
          imgUrl: '',
          description: '',
          duration: '',
          price: '',
          assetsType: 'live',
          startTime: '',
          endTime: ''
        },
        enclosureTableData: [],
        enclosureFilterTableData: [],
        disable: false,
        file: '',
        progressHidden: false,
        percentage: 0,
        enclosure: {},
        interval: '',
        options: [
          {
            value: 'live',
            label: '直播'
          },
          {
            value: 'broadcast',
            label: '录播'
          },
          {
            value: 'courseware',
            label: '课件'
          }
        ],
        rules: {
          name: [
            {required: true, message: '请输入名称', trigger: 'blur'}
          ],
          description: [
            {required: true, message: '请输入描述', trigger: 'blur'}
          ],
          duration: [
            {required: true, message: '请输入时长', trigger: 'blur'}
          ],
          price: [
            {required: true, message: '请输入价格', trigger: 'blur'}
          ],
          startTime: [
            {required: true, message: '请输入开始时间', trigger: 'blur'}
          ],
          endTime: [
            {required: true, message: '请输入结束时间', trigger: 'blur'}
          ]
        }
      }
    },
    created() {
      this.getData()
    },
    methods: {
      getData() {
        if (this.$route.params.data) {
          this.assetForm = this.$route.params.data;
          this.disable = this.$route.params.disable === 'true';
          this.getEnclosure(this.$route.params.data.id)
        }
        if (this.$route.params.categoryId) {
          this.assetForm.categoryId = this.$route.params.categoryId;
          this.assetForm.categoryName = this.$route.params.categoryName
        }
      },
      getEnclosure(id) {
        getEnclosureList(id).then(res => {
          this.enclosureTableData = res.data.items;
          this.enclosureFilterTableData = res.data.items;
          this.total = res.data.items.length
        })
      },
      // 搜索
      handleFilter() {
        this.enclosureTableData = this.enclosureFilterTableData.filter(item => {
          if (this.keyword && item.name.toLocaleLowerCase().indexOf(this.keyword.toLocaleLowerCase()) < 0) return false;
          return true
        });
        this.total = this.enclosureTableData.length
      },
      clearParams() {
        this.keyword = '';
        this.getData()
      },
      // 上传之前
      handleBefore() {
        if (!this.saveForm('courseWare')) {
          return false
        }
      },
      // 上传封面
      handleChange(file) {
        this.file = file.raw
      },
      uploadFile() {
        const fileForm = new FormData();
        fileForm.append('name', this.file.name);
        fileForm.append('uid', this.file.uid);
        fileForm.append('file', this.file);
        upLoadFile(fileForm).then(response => {
          this.assetForm.imgUrl = response.data.url
        })
      },
      uploadFileEnclosure() {
        const type = this.file.name.substring(this.file.name.lastIndexOf('.') + 1);
        const name = this.file.name.substring(0, this.file.name.lastIndexOf('.'));
        const videoArr = ['AVI', 'MKV', 'MOV', 'MP4', 'TS', 'RMVB', 'WMV', 'XVID', 'X264', 'X265', 'MPG'];
        if (videoArr.indexOf(type.toLocaleUpperCase()) !== -1) {
          const userData = '{"Vod":{}} ';
          const uploader = this.createUploader();
          uploader.addFile(this.file, null, null, null, userData);
          uploader.startUpload()
        } else {
          setTimeout(() => {
            const fileForm = new FormData();
            fileForm.append('name', name);
            fileForm.append('type', type);
            fileForm.append('file', this.file);
            fileForm.append('assetsUnitId', this.assetForm.id);
            fileForm.append('creator', getUserName());
            fileForm.append('tenantId', getTenantId());
            // this.interval = setInterval(this.showPercent, 100)
            upLoadFileToOss(fileForm).then(res => {
              this.getEnclosure(this.assetForm.id);
              this.$notify({
                title: '成功',
                message: '文件上传成功',
                type: 'success',
                duration: 2000
              })
            })
          }, 100)
        }
      },
      showPercent() {
        showPercent().then(res => {
          const end = res.data.end;
          const size = res.data.size;
          this.progressHidden = true;
          this.percentage = res.data.percent;
          if (end === -1) {
            this.progressHidden = false;
            this.percentage = 0;
            clearInterval(this.interval);
            clearPercent();
            const fileForm = new FormData();
            fileForm.append('size', size);
            fileForm.append('userId', getUserId());
            saveUsedRecord(fileForm)
          }
        }).catch(e => {
          clearInterval(this.interval);
          clearPercent();
          this.$message.error('文件上传异常')
        })
      },
      // 删除
      deleteEnclosure(row) {
        this.$confirm('确定要删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delEnclosureById(row.id, row.fileUrl).then(res => {
            this.getEnclosure(row.assetsId);
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
      },
      saveForm(val) {
        let v = false;
        this.$refs.assetForm.validate((valid) => {
          v = valid;
          if (valid) {
            if (this.assetForm.id) {
              updateAssetsUnit(this.assetForm).then(res => {
                if (val !== 'courseWare') {
                  this.$refs.assetForm.resetFields();
                  this.$router.go(-1)
                }
                this.$notify({
                  title: '成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
              })
            } else {
              this.assetForm.tenantId = getTenantId();
              this.assetForm.creator = getUserName();
              this.assetForm.belongUserId = getUserId();
              this.assetForm.belongUserName = getUserName();
              addAssetsUnit(this.assetForm).then(res => {
                if (val !== 'courseWare') {
                  this.$refs.assetForm.resetFields();
                  this.$router.go(-1)
                } else {
                  this.assetForm.id = res.data.id;
                  this.assetForm.isSplit = '0'
                }
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
              })
            }
          }
        });
        return v
      },
      cancelForm() {
        this.$refs.assetForm.resetFields();
        this.$router.go(-1)
      },
      handleSizeChange(val) {
        this.currentpage = 1;
        this.pagesize = val.value;
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      handleCurrentChange(val) {
        this.currentpage = val.value;
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      createUploader() {
        /* eslint-disable */
        const _this = this;
        const uploader = new AliyunUpload.Vod({
          timeout: 60000,
          partSize: 1048576,
          parallel: 5,
          retryCount: 3,
          retryDuration: 2,
          region: '',
          userId: '1560516061941369',

          // 添加文件成功
          addFileSuccess: function (uploadInfo) {
            // 显示上传进度
            _this.progressHidden = true;
            console.log('addFileSuccess: ' + uploadInfo.file.name + ' uploadInfo.videoId: ' + uploadInfo.videoId)
          },
          // 开始上传
          onUploadstarted: function (uploadInfo) {
            console.log('uploadInfo.videoId:' + uploadInfo.videoId);
            // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法
            // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress
            // 如果 uploadInfo.videoId 有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
            // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi
            // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)
            // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)
            if (uploadInfo.videoId) {
              // 如果videoId有值，根据videoId刷新上传凭证
              // https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
              // var refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
              getRefreshUploadVideoInfo(uploadInfo.videoId).then(res => {
                const uploadAuth = res.UploadAuth;
                const uploadAddress = res.UploadAddress;
                const videoId = res.VideoId;
                uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
              })
            } else {
              // var createUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/CreateUploadVideo?Title=testvod1&FileName=aa.mp4&BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&VideoId=5bfcc7864fc14b96972842172207c9e6'
              const title = uploadInfo.file.name.substring(0, uploadInfo.file.name.lastIndexOf('.'));
              const fileForm = new FormData();
              fileForm.append('title', title);
              fileForm.append('fileName', uploadInfo.file.name);
              getCreateUploadVideoUrl(fileForm).then(res => {
                const uploadAuth = res.data.result.UploadAuth;
                const uploadAddress = res.data.result.UploadAddress;
                const videoId = res.data.result.VideoId;
                console.log('uploadAuth' + uploadAuth + ',uploadAddress：' + uploadAddress + ',videoId：' + videoId);
                uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
              });
              console.log('onUploadStarted:' + uploadInfo.file.name + ', endpoint:' + uploadInfo.endpoint + ', bucket:' + uploadInfo.bucket + ', object:' + uploadInfo.object)
            }
          },
          // 文件上传成功
          onUploadSucceed: function (uploadInfo) {
            console.log('onUploadSucceed: ' + uploadInfo.file.name + ', endpoint:' + uploadInfo.endpoint + ', bucket:' + uploadInfo.bucket + ', object:' + uploadInfo.object);
            const endpoint = uploadInfo.endpoint.split('//')[1];
            const url = 'https://' + uploadInfo.bucket + '.' + endpoint + '/' + uploadInfo.object; // URL
            const id = uploadInfo.videoId.trim();
            const name = uploadInfo.file.name.trim();
            const assetsId = _this.assetForm.id;
            const fileForm = new FormData();
            _this.progressHidden = false;
            _this.percentage = 0;
            fileForm.append('url', url);
            fileForm.append('fileId', id);
            fileForm.append('fileName', name);
            fileForm.append('assetsUnitId', assetsId);
            fileForm.append('creator', getUserName());
            fileForm.append('tenantId', getTenantId());
            addEnclosureFromVideo(fileForm).then(res => {
              _this.getEnclosure(assetsId);
              _this.$notify({
                title: '成功',
                message: '文件上传成功',
                type: 'success',
                duration: 2000
              })
            })
          },
          // 文件上传失败
          onUploadFailed: function (uploadInfo, code, message) {
            console.log('onUploadFailed: file:' + uploadInfo.file.name + ',code:' + code + ', message:' + message);
            _this.$message.error('文件上传失败!')
          },
          // 取消文件上传
          onUploadCanceled: function (uploadInfo, code, message) {
            console.log('Canceled file: ' + uploadInfo.file.name + ', code: ' + code + ', message:' + message);
            _this.$message.warning('文件上传已暂停!')
          },
          // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
          onUploadProgress: function (uploadInfo, totalSize, progress) {
            console.log('onUploadProgress:file:' + uploadInfo.file.name + ', fileSize:' + totalSize + ', percent:' + Math.ceil(progress * 100) + '%');
            const progressPercent = Math.ceil(progress * 100);
            _this.percentage = progressPercent;
            if (progressPercent === 100) {
              const recordForm = new FormData();
              recordForm.append('size', totalSize);
              recordForm.append('userId', getUserId());
              saveUsedRecord(recordForm)
            }
            // $('.progress-bar').css('width', progressPercent + '%')
            // $('#status').text('文件上传中...')
          },
          // 上传凭证超时
          onUploadTokenExpired: function (uploadInfo) {
            // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
            // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
            // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
            _this.$message.error('文件上传超时!');
            getRefreshUploadVideoInfo(uploadInfo.videoId).then(res => {
              const uploadAuth = res.data.result.UploadAuth;
              uploader.resumeUploadWithAuth(uploadAuth);
              console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
            })
          },
          // 全部文件上传结束
          onUploadEnd: function (uploadInfo) {
            _this.$notify({title: '成功', message: '文件上传完毕!', type: 'success', duration: 2000});
            console.log('onUploadEnd: uploaded all the files')
          }
        });
        return uploader;
      }
    }
  }
</script>
<style lang="scss">
  .newassetBox {
    padding: 20px;

    .coverUpload {
      ul {
        display: none;
      }
    }

    .newClassAsset {
      ul {
        display: none;
      }
    }
  }
</style>
